import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form, Icon as LegacyIcon } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Select, Row, Col, Tree, Spin } from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { Option } = Select;
const { TreeNode } = Tree;

@connect(({ loading, role }) => ({
  loading: loading.models.role,
  // loading: loading.effects['role/fetchDetail'] || loading.effects['role/submit'] || false,
  systemList: role.systemList,
  roleInfo: role.roleInfo,
  treeData: role.treeData,
  checkedKeys: role.checkedKeys,
  expandedKeys: role.expandedKeys,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      roleId: null,
    };
  }

  componentDidMount() {
    const {
      dispatch,
      location: { query },
    } = this.props;
    const { roleId } = query;
    dispatch({
      type: 'role/fetchSystemList',
    });
    if (roleId) {
      this.setState({ roleId });
      dispatch({
        type: 'role/fetchDetail',
        payload: { roleId },
      });
    } else {
      dispatch({
        type: 'role/updateModelData',
        payload: {
          roleInfo: {},
          treeData: [],
          checkedKeys: [],
          expandedKeys: [],
        },
      });
    }
  }

  // 选择所属系统:获取授权菜单树数据
  selectSystem = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'role/updateModelData',
      payload: {
        treeData: [],
        checkedKeys: [],
        expandedKeys: [],
      },
    });
    dispatch({
      type: 'role/fetchTreeData',
      payload: { sysId: value },
    });
  };

  // 树形节点
  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode
            title={item.title}
            key={item.key}
            dataRef={item}
            icon={({ expanded }) => (
              <LegacyIcon type={expanded ? 'folder-open' : 'folder'} theme="filled" />
            )}
          >
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          {...item}
          dataRef={item}
          icon={({ expanded }) => (
            <LegacyIcon type={expanded ? 'folder-open' : 'folder'} theme="filled" />
          )}
        />
      );
    });

  // 提交数据
  submitData = () => {
    const { dispatch, form } = this.props;
    const { roleId } = this.state;
    form.validateFields((err, values) => {
      if (!err) {
        dispatch({
          type: 'role/submit',
          payload: { values, roleId },
        });
      }
    });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const {
      loading,
      form: { getFieldDecorator },
      systemList,
      roleInfo,
      treeData,
      checkedKeys,
      expandedKeys,
      dispatch,
    } = this.props;
    const { roleId } = this.state;
    return (
      <Spin tip="Loading..." spinning={loading}>
        <Form layout="horizontal">
          <PageHeaderWrapper>
            <Card
              title={<span style={{ fontWeight: 'bolder' }}> {roleId ? '修改' : '新增'}角色</span>}
              style={{ borderBottom: 'none' }}
            >
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="角色名称">
                    {getFieldDecorator('roleName', {
                      rules: [{ required: true, message: '最多不超过20字符', max: 20 }],
                      initialValue: roleInfo.roleName || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="角色类型">
                    {getFieldDecorator('roleType', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: (roleInfo.roleType && `${roleInfo.roleType}`) || undefined,
                    })(<DictCode dictType="ROLE_TYPE" />)}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="所属系统">
                    {getFieldDecorator('sysId', {
                      rules: [{ required: true, message: '请选择' }],
                      initialValue: roleInfo.sysId || undefined,
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        showSearch
                        optionFilterProp="children"
                        onSelect={this.selectSystem}
                      >
                        {systemList.length &&
                          systemList.map(item => <Option key={item.sysId}>{item.sysName}</Option>)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
              {treeData.length ? (
                <Row>
                  <Col span={17} offset={1}>
                    <FormItem {...formItemLayout} label="菜单授权">
                      {getFieldDecorator('baseRoleVo', {
                        rules: [{ required: true, message: '请选择' }],
                        initialValue: checkedKeys,
                        valuePropName: 'checkedKeys',
                        validateTrigger: 'onCheck',
                      })(
                        <Tree
                          showIcon
                          showLine
                          checkable
                          autoExpandParent
                          defaultExpandedKeys={expandedKeys}
                        >
                          {this.renderTreeNodes(treeData)}
                        </Tree>
                      )}
                    </FormItem>
                  </Col>
                </Row>
              ) : null}
              <Row>
                <Col span={17} offset={1}>
                  <FormItem {...formItemLayout} label="备注">
                    {getFieldDecorator('remark', {
                      rules: [{ required: false, message: '最多不超过200字符', max: 200 }],
                      initialValue: roleInfo.remark || undefined,
                    })(<Input placeholder="请输入" />)}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            <FooterToolbar style={{ width: '100%' }}>
              <Button
                onClick={() => {
                  dispatch({
                    type: 'role/updateModelData',
                    payload: {
                      roleInfo: {},
                      treeData: [],
                      checkedKeys: [],
                      expandedKeys: [],
                    },
                  });
                  router.goBack();
                }}
                style={{ marginRight: 10 }}
              >
                取消
              </Button>
              <Button type="primary" onClick={this.submitData}>
                保存
              </Button>
            </FooterToolbar>
          </PageHeaderWrapper>
        </Form>
      </Spin>
    );
  }
}

export default TableList;
